package com.ruoyi.rsikManage.task;

import com.alibaba.fastjson2.JSONObject;
//import com.ruoyi.rsikManage.service.JyService;
import com.ruoyi.common.GenericMethodsService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.rsikManage.domain.AlarmSendingUrlConfig;
import com.ruoyi.rsikManage.domain.TUnitConfig;
import com.ruoyi.rsikManage.service.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class JYTokenScheduler implements InitializingBean {
    @Autowired
    ServletContext servletContext;
    @Autowired
    JyService jyService;
    @Autowired
    IAlarmSendingUrlService iAlarmSendingUrlService;
    @Autowired
    MonitorPointService monitorPointService;
    @Autowired
    ConfigService configService;
    @Autowired
    BroadcastService broadcastService;

    @Value("${broadcast.switch}")
    private boolean BroadcastSwitch;

    @Autowired
    ITUnitConfigService tUnitConfigService;

    @Autowired
    TokenService tokenService;

    @Autowired
    private GenericMethodsService genericMethodsService;
    /**
     * 项目启动时获取到访问极云的Token，将其存储在servletContext中
     * 公共示例
     */
//    @Override
    public void afterPropertiesSet2() throws Exception {
        String jsonStr = jyService.getAccessToken();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        //将 access_token 和 refresh_token 设置到容器中
        String accessToken = jsonObject.getString("access_token");
        String refresh_token = jsonObject.getString("refresh_token");
        jsonObject.getString("access_token");
        if (accessToken != null) {
            servletContext.setAttribute("access_token", accessToken);
            servletContext.setAttribute("refresh_token",refresh_token);
            System.out.println("访问极云的Token是" + accessToken);
            System.out.println("访问极云的refreshToken是" + refresh_token);
        }
        //
        try {
            List<AlarmSendingUrlConfig> alarmSendingUrlList = iAlarmSendingUrlService.selectAlarmSendingUrlList(new AlarmSendingUrlConfig().setAlarmType("1"));
            servletContext.setAttribute("urlListWhereTheAlarmInfoIsSent", alarmSendingUrlList);
        }catch (Exception e) {
            servletContext.setAttribute("urlListWhereTheAlarmInfoIsSent", null);
        }
        //
        try {
            if(BroadcastSwitch){
                broadcastService.updateBroadCastList();
            }

        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("更新广播列表失败");;
        }
        //
        try {
            int broadcastPlaySwitch = configService.getBroadcastPlaySwitchStatus();
            servletContext.setAttribute("broadcastPlaySwitch", broadcastPlaySwitch);
            System.out.println("-----------广播播报开关为-----------: " + broadcastPlaySwitch);
        }catch (Exception e) {
            servletContext.setAttribute("broadcastPlaySwitch", 1);
            e.printStackTrace();
        }

    }

//
    /**
     * 项目启动时获取访问极云的Token，并将其存储在servletContext中。
     * 同时初始化一些与报警和广播相关的配置。
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        // 从极云服务获取访问Token的JSON字符串

        Map<Long, SysDept> deptMap = genericMethodsService.getDeptMap();
        // 将 Map 转换为 List
        List<SysDept> deptList = deptMap.values().stream().collect(Collectors.toList());
        List<Long> unitCodes = new ArrayList<>();
        for (SysDept dept:deptList){
            unitCodes.add(dept.getUnitCode());
        }

        TUnitConfig tUnitConfig = new TUnitConfig();
        tUnitConfig.setUnitCodes(unitCodes);

        List<TUnitConfig> tUnitConfigs = tUnitConfigService.selectTUnitConfigList(tUnitConfig);
        for (TUnitConfig unit : tUnitConfigs) {
            Long unitCode = unit.getUnitCode();
            try {
                String jsonStr = jyService.getAccessTokenForUnitCodes(unit);
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);

                // 提取access_token和refresh_token，并存储到servletContext中
                String accessToken = jsonObject.getString("access_token");
                String refreshToken = jsonObject.getString("refresh_token");

                if (accessToken != null) {
                    // 设置access_token和refresh_token到servletContext
                    servletContext.setAttribute(unitCode + "_" + "access_token", accessToken);
                    servletContext.setAttribute(unitCode + "_" + "refresh_token", refreshToken);
                    System.out.println(unitCode + "访问极云的Token是" + accessToken);
                    System.out.println(unitCode + "访问极云的refreshToken是" + refreshToken);
                }
            } catch (Exception e) {
                // 记录异常信息，但继续处理下一个unit
                System.err.println("获取 " + unitCode + " 的Token时发生异常: " + e.getMessage());
                // 可以选择记录更详细的异常信息
                // e.printStackTrace();
            }
        }
//
        /**
         *  暂不发送报警 代码进行注释
         */
//        // 尝试获取报警发送URL列表并存储到servletContext
//        try {
//            List<AlarmSendingUrlConfig> alarmSendingUrlList = iAlarmSendingUrlService.selectAlarmSendingUrlList(new AlarmSendingUrlConfig().setAlarmType("1"));
//            servletContext.setAttribute("urlListWhereTheAlarmInfoIsSent", alarmSendingUrlList);
//        } catch (Exception e) {
//            // 若获取失败，设置为null
//            servletContext.setAttribute("urlListWhereTheAlarmInfoIsSent", null);
//        }

        /**
         *  暂不尝试更新广播列表 代码进行注释
         *  时间 24/10/24
         */

        try {
            if (BroadcastSwitch) {
                broadcastService.updateBroadCastList();
            }
        } catch (Exception e) {
            // 捕获异常并打印错误信息
            e.printStackTrace();
            System.out.println("更新广播列表失败");
        }
        /**
         *  暂不尝试获取广播播放开关状态并存储到servletContext 代码进行注释
         *  时间 24/10/24
         */

        try {
            int broadcastPlaySwitch = configService.getBroadcastPlaySwitchStatus();
            servletContext.setAttribute("broadcastPlaySwitch", broadcastPlaySwitch);
            System.out.println("-----------广播播报开关为-----------: " + broadcastPlaySwitch);
        } catch (Exception e) {
            // 若获取失败，默认为1
            servletContext.setAttribute("broadcastPlaySwitch", 1);
            e.printStackTrace();
        }
    }

    /**
     * 每一小时刷新一次token
     *
     * 代码进行注释
     * 时间 24/10/24
     */
//    @Scheduled(cron = "0 0 */1 * * ?")
//    public void refreshTokenEveryNinetyMinutes() {
//        String jsonStr = jyService.getNewAccessToken();
//        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
//        String access_token = jsonObject.getString("access_token");
//        String refresh_token = jsonObject.getString("refresh_token");
//
//        if (access_token != null) {
//            servletContext.setAttribute("access_token", access_token);
//            servletContext.setAttribute("refresh_token",refresh_token);
//            System.out.println("新的极云access_token是:" + (String) servletContext.getAttribute("access_token"));
//            System.out.println("新的极云access_token是:" + (String) servletContext.getAttribute("refresh_token"));
//        }
//    }

    /**
     * 每一小时刷新一次token
     */
    @Scheduled(cron = "0 0 */1 * * ?")
    public void refreshTokenEveryNinetyMinutes() {

        Map<Long, SysDept> deptMap = genericMethodsService.getDeptMap();
        // 将 Map 转换为 List
        List<SysDept> deptList = deptMap.values().stream().collect(Collectors.toList());
        List<Long> unitCodes = new ArrayList<>();
        for (SysDept dept:deptList){
            unitCodes.add(dept.getUnitCode());
        }

        TUnitConfig tUnitConfig = new TUnitConfig();
        tUnitConfig.setUnitCodes(unitCodes);

        List<TUnitConfig> tUnitConfigs = tUnitConfigService.selectTUnitConfigList(tUnitConfig);

        for (TUnitConfig unit : tUnitConfigs) {
            Long unitCode = unit.getUnitCode();
            try {
                String jsonStr = jyService.getNewAccessTokenForUnitCodes(unit);
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                String access_token = jsonObject.getString("access_token");
                String refresh_token = jsonObject.getString("refresh_token");

                if (access_token != null) {
                    servletContext.setAttribute(unitCode + "_" + "access_token", access_token);
                    servletContext.setAttribute(unitCode + "_" + "refresh_token", refresh_token);
                    System.out.println("新的极云access_token是: " + (String) servletContext.getAttribute(unitCode + "_" + "access_token"));
                    System.out.println("新的极云refresh_token是: " + (String) servletContext.getAttribute(unitCode + "_" + "refresh_token"));
                }
            } catch (Exception e) {
                // 记录异常信息，但继续处理下一个unit
                System.err.println("获取 " + unitCode + " 的Token时发生异常: " + e.getMessage());
                // 可以选择记录更详细的异常信息
                // e.printStackTrace();
            }
        }

    }

}
